package warmachineroster.presentation.policy;

import java.util.List;

import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.commands.CompoundCommand;
import org.eclipse.gef.commands.UnexecutableCommand;
import org.eclipse.gef.editpolicies.FlowLayoutEditPolicy;
import org.eclipse.gef.requests.CreateRequest;

import warmachineroster.Roster;
import warmachineroster.RosterElement;
import warmachineroster.UnitRosterElement;
import warmachineroster.WarcasterRosterElement;
import warmachineroster.presentation.command.RosterElementCreateCommand;
import warmachineroster.presentation.command.RosterElementMoveCommand;
import warmachineroster.presentation.editpart.RosterEditPart;
import warmachinesystem.BaseUnit;
import warmachinesystem.Solo;

public class RoosterLayoutEditPolicy extends FlowLayoutEditPolicy implements
		EditPolicy {

	@Override
	protected Command createAddCommand(EditPart child, EditPart after) {
		return UnexecutableCommand.INSTANCE;
	}

	@Override
	protected Command createMoveChildCommand(EditPart child, EditPart after) {
		if (after != null)
		{
			RosterElement childModel = (RosterElement) child.getModel();

			Roster roster = (Roster) getHost().getModel();
			int oldIndex = getHost().getChildren().indexOf(child);
			int newIndex = getHost().getChildren().indexOf(after);

			RosterElementMoveCommand command = new RosterElementMoveCommand();
			command.setRoster(roster);
			command.setElement(childModel);
			command.setOldIndex(oldIndex);
			command.setNewIndex(newIndex);
			
			return command;
		}
		return null;
	}

	@Override
	protected Command getCreateCommand(CreateRequest request) {
		Object newObject = request.getNewObject();
		Command result = null;
		result = getCreateCommand(newObject);
		return result;
	}

	private Command getCreateCommand(Object newObject) {
		if (newObject instanceof WarcasterRosterElement || newObject instanceof UnitRosterElement ){
			RosterElementCreateCommand command = new RosterElementCreateCommand();
			command.setRosterElement((RosterElement) newObject);
			RosterEditPart rosterEditPart = (RosterEditPart) getHost();
			command.setRoster(rosterEditPart.getRoster());
			return command;
		}else if (newObject instanceof RosterElement){
			BaseUnit bu = ((RosterElement)newObject).getUnitType();
			if (bu instanceof Solo){
				RosterElementCreateCommand command = new RosterElementCreateCommand();
				command.setRosterElement((RosterElement) newObject);
				RosterEditPart rosterEditPart = (RosterEditPart) getHost();
				command.setRoster(rosterEditPart.getRoster());
				return command;
			}
				
		} else if (newObject instanceof List){
			CompoundCommand ccommand = new CompoundCommand();
			for(Object elem: (List<?>)newObject){
				ccommand.add(getCreateCommand(elem));
			}
			return ccommand;
		}
		return UnexecutableCommand.INSTANCE;
	}

}
